<?php

namespace App\Providers;

use Dingo\Api\Facade\API;
use Illuminate\Support\ServiceProvider;

class ErrorServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 接管dingo api 产生的异常
        API::error(function (\Illuminate\Validation\ValidationException $exception) {
            $data = $exception->validator->getMessageBag();
            $msg = collect($data)->first();
            if (is_array($msg)) {
                $msg = $msg[0];
            }
            return response()->json(['message' => $msg, 'code' => 422], 200);
        });
        API::error(function (\Dingo\Api\Exception\ValidationHttpException $exception) {
            $errors = $exception->getErrors();
            return response()->json(['message' => $errors->first(), 'code' => 422], 200);
        });
        // 接管自定义异常
        API::error(function (\App\Exceptions\BaseException $exception) {
            $error = $exception->getExceptionMessage();
            return response()->json(['message' => $error, 'code' => $exception->getCode()], $exception->status);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

    }
}
